﻿using System;
using Csla;
using BizControl.Library.BusinessObjects.Activities;
using BizControl.DalLinq;
using BizControl.Resources;
using System.Linq;
using BizControl.Library.BusinessObjects.BusinessRoles;
using BizControl.Library.BusinessObjects.People;
using System.Collections.Generic;

namespace BizControl.Library.BusinessObjects.Participants
{
  [Serializable()]
  public class ActivityParticipants : BusinessListBase<ActivityParticipants, ParticipantBO>
  {
    #region  Business Methods

    private ActivityBO _activity;

    public ParticipantBO AddParticipant()
    {
      ParticipantBO participant = ParticipantBO.NewParticipant(_activity);
      this.Add(participant);
      return participant;
    }

    public ParticipantBO this[Guid participantSearchFor]
    {
      get
      {
        foreach (ParticipantBO participant in this)
        {
          if (participant.ParticipantId == participantSearchFor)
            return participant;
        }
        return null;
      }
    }

    #endregion

    #region  Factory Methods

    internal static ActivityParticipants NewActivityParticipants(ActivityBO activity)
    {
      return DataPortal.CreateChild<ActivityParticipants>(activity);
    }

    internal static ActivityParticipants GetActivityParticipants(Participant[] data, ActivityBO activity)
    {
      return DataPortal.FetchChild<ActivityParticipants>(data, activity);
    }

    internal static ActivityParticipants CopyParticipants(ActivityBO newActivity, ActivityBO sourceActivity, ref Dictionary<Guid, Guid> participantPairs)
    {
      var newParticipants = DataPortal.CreateChild<ActivityParticipants>(newActivity);
      foreach (var participant in sourceActivity.Participants)
      {
        var newPaticipant = newParticipants.AddParticipant();
        newPaticipant.Person = new PersonInfo(participant.Person);
        newPaticipant.Role = new BusinessRoleInfo(participant.Role);
        participantPairs.Add(participant.ParticipantId, newPaticipant.ParticipantId);
      }
      return newParticipants;
    }

    private ActivityParticipants()
    { /* require use of factory methods */ }

    #endregion

    #region  Data Access

    private void Child_Create(ActivityBO activity)
    {
      if (activity == null) throw new ArgumentNullException(ExceptionsMessages.ActivityNullReference);
      _activity = activity;
    }

    private void Child_Fetch(Participant[] data, ActivityBO activity)
    {
      if (activity == null) throw new ArgumentNullException(ExceptionsMessages.ActivityNullReference);
      _activity = activity;
      if (data == null) return;
      this.RaiseListChangedEvents = false;
      foreach (var child in data)
        Add(ParticipantBO.GetParticipant(child, _activity));
      this.RaiseListChangedEvents = true;
    }

    #endregion
  }
}
